<template>
  <div class="api-log-container">
    <a-card class="filter-card">
      <a-row :gutter="20">
        <a-col :span="5">
          <a-range-picker
            v-model:value="dateRange"
            style="width: 100%"
            :placeholder="['开始时间', '结束时间']"
          />
        </a-col>
        <a-col :span="4">
          <a-select
            v-model:value="methodFilter"
            placeholder="请求方法"
            allow-clear
            style="width: 100%"
          >
            <a-select-option value="GET">GET</a-select-option>
            <a-select-option value="POST">POST</a-select-option>
            <a-select-option value="PUT">PUT</a-select-option>
            <a-select-option value="DELETE">DELETE</a-select-option>
          </a-select>
        </a-col>
        <a-col :span="4">
          <a-select
            v-model:value="statusFilter"
            placeholder="状态码"
            allow-clear
            style="width: 100%"
          >
            <a-select-option value="200">200</a-select-option>
            <a-select-option value="400">400</a-select-option>
            <a-select-option value="401">401</a-select-option>
            <a-select-option value="403">403</a-select-option>
            <a-select-option value="404">404</a-select-option>
            <a-select-option value="500">500</a-select-option>
          </a-select>
        </a-col>
        <a-col :span="5">
          <a-input-search
            v-model:value="urlFilter"
            placeholder="搜索URL"
            allow-clear
          />
        </a-col>
        <a-col :span="4">
          <a-button @click="filterLogs">搜索</a-button>
          <a-button style="margin-left: 10px" @click="resetFilters">重置</a-button>
        </a-col>
        <a-col :span="2" class="text-right">
          <a-dropdown>
            <template #overlay>
              <a-menu>
                <a-menu-item key="1" @click="exportLogs('current')">导出当前页</a-menu-item>
                <a-menu-item key="2" @click="exportLogs('all')">导出全部</a-menu-item>
              </a-menu>
            </template>
            <a-button>
              导出
              <DownOutlined />
            </a-button>
          </a-dropdown>
        </a-col>
      </a-row>
    </a-card>

    <a-card class="content-card">
      <a-table
        :data-source="logList"
        :columns="columns"
        :pagination="pagination"
        @change="handleTableChange"
        :loading="loading"
        :scroll="{ x: 1200 }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'method'">
            <a-tag :color="getMethodColor(record.method)">{{ record.method }}</a-tag>
          </template>
          <template v-else-if="column.dataIndex === 'status'">
            <a-tag :color="getStatusColor(record.status)">{{ record.status }}</a-tag>
          </template>
          <template v-else-if="column.dataIndex === 'action'">
            <a-button type="link" @click="viewDetail(record)">详情</a-button>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 日志详情 Modal -->
    <a-modal
      v-model:open="detailModalVisible"
      title="调用详情"
      width="800px"
      @cancel="handleDetailModalCancel"
    >
      <a-tabs v-model:activeKey="detailTab">
        <a-tab-pane key="1" tab="基本信息">
          <a-descriptions :column="1" bordered>
            <a-descriptions-item label="请求ID">{{ currentLog.id }}</a-descriptions-item>
            <a-descriptions-item label="请求时间">{{ currentLog.time }}</a-descriptions-item>
            <a-descriptions-item label="请求方法">
              <a-tag :color="getMethodColor(currentLog.method)">{{ currentLog.method }}</a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="请求URL">{{ currentLog.url }}</a-descriptions-item>
            <a-descriptions-item label="状态码">
              <a-tag :color="getStatusColor(currentLog.status)">{{ currentLog.status }}</a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="耗时">{{ currentLog.duration }}ms</a-descriptions-item>
            <a-descriptions-item label="客户端IP">{{ currentLog.clientIp }}</a-descriptions-item>
            <a-descriptions-item label="用户代理">{{ currentLog.userAgent }}</a-descriptions-item>
          </a-descriptions>
        </a-tab-pane>
        <a-tab-pane key="2" tab="请求信息">
          <a-descriptions title="请求头" :column="1">
            <a-descriptions-item v-for="(value, key) in currentLog.requestHeaders" :key="key" :label="key">
              {{ value }}
            </a-descriptions-item>
          </a-descriptions>
          <a-divider />
          <div v-if="currentLog.requestBody">
            <h4>请求体</h4>
            <pre class="code-block">{{ currentLog.requestBody }}</pre>
          </div>
        </a-tab-pane>
        <a-tab-pane key="3" tab="响应信息">
          <a-descriptions title="响应头" :column="1">
            <a-descriptions-item v-for="(value, key) in currentLog.responseHeaders" :key="key" :label="key">
              {{ value }}
            </a-descriptions-item>
          </a-descriptions>
          <a-divider />
          <div v-if="currentLog.responseBody">
            <h4>响应体</h4>
            <pre class="code-block">{{ currentLog.responseBody }}</pre>
          </div>
        </a-tab-pane>
      </a-tabs>
    </a-modal>
  </div>
</template>

<script>
import { DownOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import dayjs from 'dayjs';

export default {
  name: 'ApiLog',
  components: {
    DownOutlined
  },
  data() {
    return {
      dateRange: [dayjs().subtract(7, 'day'), dayjs()],
      methodFilter: undefined,
      statusFilter: undefined,
      urlFilter: '',
      loading: false,
      detailModalVisible: false,
      detailTab: '1',
      currentLog: {},
      logList: [
        {
          id: 'REQ202309010001',
          time: '2023-09-01 10:30:25',
          method: 'GET',
          url: '/api/users',
          status: 200,
          duration: 120,
          clientIp: '192.168.1.100',
          userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
          requestHeaders: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer xxxxxx'
          },
          requestBody: '',
          responseHeaders: {
            'Content-Type': 'application/json',
            'Content-Length': '1234'
          },
          responseBody: '{\n  "code": 200,\n  "message": "success",\n  "data": []\n}'
        },
        {
          id: 'REQ202309010002',
          time: '2023-09-01 10:32:10',
          method: 'POST',
          url: '/api/users',
          status: 201,
          duration: 250,
          clientIp: '192.168.1.101',
          userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36',
          requestHeaders: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer xxxxxx'
          },
          requestBody: '{\n  "name": "张三",\n  "email": "zhangsan@example.com"\n}',
          responseHeaders: {
            'Content-Type': 'application/json',
            'Content-Length': '234'
          },
          responseBody: '{\n  "code": 201,\n  "message": "created",\n  "data": {\n    "id": 1001\n  }\n}'
        },
        {
          id: 'REQ202309010003',
          time: '2023-09-01 10:35:45',
          method: 'PUT',
          url: '/api/users/1001',
          status: 400,
          duration: 80,
          clientIp: '192.168.1.102',
          userAgent: 'PostmanRuntime/7.29.0',
          requestHeaders: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer xxxxxx'
          },
          requestBody: '{\n  "name": "",\n  "email": "invalid-email"\n}',
          responseHeaders: {
            'Content-Type': 'application/json',
            'Content-Length': '156'
          },
          responseBody: '{\n  "code": 400,\n  "message": "参数校验失败",\n  "data": null\n}'
        }
      ],
      columns: [
        {
          title: '请求ID',
          dataIndex: 'id',
          key: 'id',
          width: 180
        },
        {
          title: '请求时间',
          dataIndex: 'time',
          key: 'time',
          width: 180
        },
        {
          title: '方法',
          dataIndex: 'method',
          key: 'method',
          width: 100
        },
        {
          title: 'URL',
          dataIndex: 'url',
          key: 'url',
          width: 250
        },
        {
          title: '状态码',
          dataIndex: 'status',
          key: 'status',
          width: 100
        },
        {
          title: '耗时(ms)',
          dataIndex: 'duration',
          key: 'duration',
          width: 120
        },
        {
          title: '客户端IP',
          dataIndex: 'clientIp',
          key: 'clientIp',
          width: 150
        },
        {
          title: '操作',
          dataIndex: 'action',
          key: 'action',
          width: 100
        }
      ],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 3
      }
    };
  },
  methods: {
    filterLogs() {
      message.success('搜索成功');
    },
    resetFilters() {
      this.methodFilter = undefined;
      this.statusFilter = undefined;
      this.urlFilter = '';
      this.dateRange = [dayjs().subtract(7, 'day'), dayjs()];
      message.success('重置成功');
    },
    exportLogs(type) {
      message.success(`导出${type === 'current' ? '当前页' : '全部'}日志成功`);
    },
    viewDetail(record) {
      this.currentLog = record;
      this.detailModalVisible = true;
    },
    handleDetailModalCancel() {
      this.detailModalVisible = false;
    },
    handleTableChange(pagination) {
      this.pagination = { ...pagination };
    },
    getMethodColor(method) {
      const colorMap = {
        GET: 'blue',
        POST: 'green',
        PUT: 'orange',
        DELETE: 'red'
      };
      return colorMap[method] || 'default';
    },
    getStatusColor(status) {
      if (status >= 200 && status < 300) {
        return 'success';
      } else if (status >= 400 && status < 500) {
        return 'warning';
      } else if (status >= 500) {
        return 'error';
      }
      return 'default';
    }
  }
};
</script>

<style scoped>
.api-log-container {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.content-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.text-right {
  text-align: right;
}

.code-block {
  background-color: #f5f5f5;
  padding: 15px;
  border-radius: 4px;
  max-height: 300px;
  overflow-y: auto;
  white-space: pre-wrap;
}
</style>